<!--
  功能：上传图片
  时间：2023年03月16日 15:22:48
-->
<template>
  <el-upload
    :headers="data"
    :on-success="imgSuccess"
    :multiple="true"
    :before-upload="beforeUploadFn"
    :show-file-list="false"
    :action="config.baseUrl + 'api/img/upImg'"
    :auto-upload="true"
  >
    <el-button type="primary">多图上传</el-button>
  </el-upload>
</template>

<script lang="ts" setup>
import config from "@/common/config";
import type { requeryRes } from "@/common/interface";
import { ElMessage } from "element-plus";

const emit = defineEmits<{
  (e: "img", data?: { imgUrl: string }): void; //向父组件传递 已选择的图片
}>();


const data = ref({
  lang: localStorage.getItem('lang'),
  token: localStorage.getItem('token'),
  client: "admin",
});

//图片上传之前
//图片上传之前
async function beforeUploadFn(file: HTMLInputElement) {
  //获取文件后缀
  let index = file.type.lastIndexOf("/");
  let type = file.type.substring(index + 1, file.type.length);
  const isJPG =
    file.type === "image/jpeg" ||
    file.type === "image/png" ||
    file.type === "image/gif" ||
    file.type === "image/webp";
  if (!isJPG) {
    ElMessage.error("文件只能是 jpeg、png、gif 格式!");
    return false;
  }
  const isLt1M = file.size / 1024 / 1024 < 1;
  if (!isLt1M) {
    ElMessage.error("上传图片大小不能超过 1MB!");
    return false;
  }

  return isJPG && isLt1M;
}

//图片上传
function imgSuccess(data:requeryRes) {
  emit('img')
}
</script>
